import 'dart:math';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';

class LineChartSample2 extends StatefulWidget {
  final List<double> spots; // 新增参数
  final List<String> xTitle; // 更新参数类型为非空
  final double aspectRatio; // 统计图宽高比

  const LineChartSample2(
      {super.key,
      required this.spots,
      required this.xTitle,
      this.aspectRatio = 1.70}); // 更新构造函数，设置默认值

  @override
  State<LineChartSample2> createState() => _LineChartSample2State();
}

class _LineChartSample2State extends State<LineChartSample2> {
  List<Color> gradientColors = [
    Colors.white,
    Colors.blue,
  ];

  List<FlSpot> xdata = [
    FlSpot(0, 0),
    FlSpot(20, 0),
    FlSpot(40, 0),
    FlSpot(60, 0),
    FlSpot(80, 0),
    FlSpot(100, 0)
  ]; // 初始化 xdata 为一个空列表
  List<double> xRate = [0, 20, 40, 60, 80, 100];

  bool showAvg = false;

  @override
  Widget build(BuildContext context) {
    if (widget.spots.isNotEmpty) {
      xdata = [];
      xRate = [];
      final int len = (100 / (widget.spots.length - 1)).toInt();
      for (int i = 0; i < widget.spots.length; i++) {
        xdata.add(FlSpot(i * len.toDouble() ,
            widget.spots[i]));
        xRate.add(i * len.toDouble());
      }
    }
    return Stack(
      children: <Widget>[
        AspectRatio(
          aspectRatio: widget.aspectRatio,
          child: Padding(
            padding: const EdgeInsets.only(
              top: 10,
              left: 10,
              right: 10,
              bottom: 10,
            ),
            child: LineChart(
              mainData(),
            ),
          ),
        ),
        // SizedBox(
        //   width: 60,
        //   height: 34,
        //   child: TextButton(
        //     onPressed: () {
        //       setState(() {
        //         showAvg = !showAvg;
        //       });
        //     },
        //     child: Text(
        //       'avg',
        //       style: TextStyle(
        //         fontSize: 12,
        //         color: Colors.white,
        //       ),
        //     ),
        //   ),
        // ),
      ],
    );
  }

  Widget bottomTitleWidgets(double value, TitleMeta meta) {
    const style = TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: 11,
      color: Color(0xFF65CEFF),
    );
    Widget text = const Text('', style: style);
    for (int i = 0; i < xRate.length; i++) {
      if (value.toInt() == xRate[i]) {
        text = Text(widget.xTitle[i], style: style);
        break;
      }
    }
    return SideTitleWidget(
      axisSide: meta.axisSide,
      child: text,
    );
  }

  Widget leftTitleWidgets(double value, TitleMeta meta) {
    const style = TextStyle(
      fontSize: 11,
      color: Colors.grey,
    );
    String text;
    switch (value.toInt()) {
      case 0:
        text = '00';
        break;
      case 20:
        text = '20';
        break;
      case 40:
        text = '40';
        break;
      case 60:
        text = '60';
        break;
      case 80:
        text = '80';
        break;
      case 100:
        text = '100';
        break;
      default:
        return Container();
    }

    return Text(text, style: style, textAlign: TextAlign.left);
  }

  LineChartData mainData() {
    return LineChartData(
      gridData: FlGridData(
        show: true,
        drawVerticalLine: true,
        horizontalInterval: 1,
        verticalInterval: 1,
        getDrawingHorizontalLine: (value) {
          return const FlLine(
            color: Colors.grey,
            strokeWidth: 0,
          );
        },
        getDrawingVerticalLine: (value) {
          return const FlLine(
            color: Colors.grey,
            strokeWidth: 0,
          );
        },
      ),
      titlesData: FlTitlesData(
        show: true,
        rightTitles: const AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
        topTitles: const AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 30,
            interval: 1,
            getTitlesWidget: bottomTitleWidgets,
          ),
        ),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            interval: 1,
            getTitlesWidget: leftTitleWidgets,
            reservedSize: 42,
          ),
        ),
      ),
      borderData: FlBorderData(
        show: false, // 隐藏边框--外边框
        border: Border.all(color: const Color(0xff37434d)),
      ),
      minX: 0,
      maxX: 100,
      minY: 0,
      maxY: 100,
      lineBarsData: [
        LineChartBarData(
          spots: xdata, // 使用传入的 spots
          isCurved: true,
          gradient: LinearGradient(
            colors: [Colors.blue, Colors.blue],
          ),
          barWidth: 1,

          /// 顶部线条宽度
          isStrokeCapRound: true,
          dotData: const FlDotData(
            show: true,
          ),
          belowBarData: BarAreaData(
            show: false,
            gradient: LinearGradient(
              colors: [
                Colors.blue,
                Colors.white,
              ] //gradientColors
                  // .map((color) => color.withOpacity(0.3))
                  .toList(),
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
        ),
      ],
    );
  }
}
